
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLEService.h>
#include <BLECharacteristic.h>
#include "BLE2902.h"

#define SERVICE_UUID "b408e1a0-3d8a-11ed-b878-0242ac120002"
#define CHARACTERISTIC_UUID "de045162-3d97-11ed-b878-0242ac120002"


class ServerCallback: public BLEServerCallbacks{
  void onConnect(BLEServer* server) {
    Serial.println("DEVICE_CONNECTED~");
    BLEDevice::stopAdvertising();
  }

  void onDisconnect(BLEServer* server) {
    Serial.println("DEVICE_DISCONNECT~");
    BLEDevice::startAdvertising();
  }
};

class CharticCallback: public BLECharacteristicCallbacks{
  void onRead(BLECharacteristic * characteristic){
    Serial.println("ON_READ~");
  }

  void onWrite(BLECharacteristic * characteristic){
    std::string data=characteristic->getValue();
    if(data.length()>0){
      String strs="";
      for (int i = 0; i < data.length(); i++){
        strs += (char)data[i];
      }
      Serial.println("get data:"+strs);
    }
    Serial.println("data:"+String(data.c_str()));

    characteristic->setValue("hfk567");
    characteristic->notify();
  }
};

BLECharacteristic chartic(CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY);

//设置服务器所需要的配置
void setup() {
  Serial.begin(115200);
  BLEDevice::init("BLE_FROM_ESP32");
  BLEServer *server = BLEDevice::createServer();
  BLEService *service = server->createService(SERVICE_UUID);

  service->addCharacteristic(&chartic);
  chartic.addDescriptor(new BLE2902());

  server->setCallbacks(new ServerCallback());
  chartic.setCallbacks(new CharticCallback());

  service->start();
  BLEDevice::startAdvertising();

  Serial.println("Characteristic defined! Now you can test it in your phone!");
}

void loop() {

}